/**
 * Copyright (c)2014 快诺迅汇(长沙)网络技术股份有限公司。
 * 版权所有
 */
package com.lehe.controller;

import com.lehe.common.Contants;
import com.lehe.common.crypt.AesException;
import com.lehe.common.crypt.WXBizMsgCrypt;
import com.lehe.common.enums.CodeMappingClass;
import com.lehe.common.enums.WeChatMsgTypeEnum;
import com.lehe.common.utils.SpringContextUtil;
import com.lehe.common.utils.StringUtil;
import com.lehe.entry.wx.message.ReqEventPushMessage;
import com.lehe.entry.wx.message.RespBaseMessage;
import com.lehe.service.IMessageConvert;
import com.lehe.service.IWeChatExecuteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 类的功能描述<br>
 *
 * @author 王丹
 * @FileName WeiXinController.java<br>
 * @Language Java<br>
 * @date 2016-07-22<br>
 */
@Controller
@RequestMapping("/weixin")
public class WeiXinController extends Basecontroller {

    @Autowired
    protected IMessageConvert messageConvert;

    @RequestMapping(value = "", method = RequestMethod.GET)
    public String index(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("RemoteAddr: " + request.getRemoteAddr());
        logger.info("QueryString: " + request.getQueryString());
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");

        WXBizMsgCrypt wxBizMsgCrypt = null;
        try {
            wxBizMsgCrypt = new WXBizMsgCrypt(Contants.TOKEN_FOR_KWINER, Contants.AES_KEY_FOR_KWINER, Contants.APP_ID);
            makeResponse(response, "text/html", wxBizMsgCrypt.verifyUrl(signature, timestamp, nonce, echostr, false));
        } catch (AesException e) {
            e.printStackTrace();
            makeResponse(response, "text/html", "fail");
        }
        return null;
    }

    @RequestMapping(value = "", method = RequestMethod.POST)
    public void weChatRecive(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String respStr = "success";
        RespBaseMessage respMessage = new RespBaseMessage();
        String requestContent = getRequestContent(request);
        logger.info("接收到微信服务Post请求参数：" + requestContent);
        try {
            String msgType = StringUtil.getTagText(requestContent, "MsgType");
            logger.info("msgType=" + msgType);
            IWeChatExecuteService weChatExecuteService = null;
            if(WeChatMsgTypeEnum.EVENT.name().equalsIgnoreCase(msgType)){
                ReqEventPushMessage reqEventPushMessage = messageConvert.convertFromXml(ReqEventPushMessage.class, requestContent);
                CodeMappingClass codeMappingClass = CodeMappingClass.queryCodeMappingClass(reqEventPushMessage.getMsgType() + "_" + reqEventPushMessage.getEvent());
                logger.info("codeMappingClass=" + codeMappingClass);
                if(null != codeMappingClass){
                    weChatExecuteService = SpringContextUtil.getBean(StringUtil.firstCharToLower(codeMappingClass.getExecuteClass()));
                    if(null != weChatExecuteService){
                        respMessage = weChatExecuteService.execute(reqEventPushMessage);
                        respStr = messageConvert.convertToXml(respMessage);
                    }
                }
            }else if(WeChatMsgTypeEnum.TEXT.name().equalsIgnoreCase(msgType)){
//                ReqMsgPushMessage reqMsgPushMessage = messageConvert.convertFromXml(ReqMsgPushMessage.class, requestContent);
//                CodeMappingClass codeMappingClass = CodeMappingClass.queryCodeMappingClass(msgType);
//                logger.info("codeMappingClass=" + codeMappingClass);
//                weChatExecuteService = SpringContextUtil.getBean(StringUtil.firstCharToLower(codeMappingClass.getExecuteClass()));
//                respMessage = weChatExecuteService.execute(reqMsgPushMessage);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("系统接收微信推送异常", e);
            respMessage.setErrmsg(e.getMessage());
            //respStr = e.getMessage();
        }
        logger.info("返回微信服务器信息:" + respStr);
        //回复空串告诉微信服务器本次请求处理成功
        makeResponse(response, "text/xml", respStr);
    }
}
